import json
from django.core.management.base import BaseCommand
from django.utils import timezone
from system.models import Role, RolePermission, Menu  # 请将 your_app 替换为你的应用名称


class Command(BaseCommand):
    help = 'Import roles from role.json file'

    def handle(self, *args, **options):
        try:
            # 打开并读取 role.json 文件
            with open('sql/role.json', 'r', encoding='utf-8') as file:
                data = json.load(file)
                items = data.get('data', {}).get('items', [])

                for item in items:
                    # 提取需要的数据
                    name = item.get('name')
                    status = item.get('status')
                    create_time_str = item.get('createTime')
                    remark = item.get('remark')
                    permission_codes = item.get('permissions', [])

                    # 创建新的 Role 实例
                    role = Role.objects.create(
                        name=name,
                        status=status,
                        remark=remark
                    )

                    # 处理权限关联
                    for code in permission_codes:
                        try:
                            # 假设 Menu 模型有一个 auth_code 字段来匹配权限代码
                            menu = Menu.objects.get(auth_code=code)
                            RolePermission.objects.create(
                                role=role,
                                menu=menu
                            )
                        except Menu.DoesNotExist:
                            self.stderr.write(self.style.WARNING(f"Menu with auth_code {code} not found."))

                self.stdout.write(self.style.SUCCESS('Roles imported successfully.'))
        except Exception as e:
            self.stderr.write(self.style.ERROR(f'Error importing roles: {e}'))